package v1

import (
	"context"
	"encoding/csv"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"net/http"
	"os"
	"time"
)

type AdjustRes struct {
	Language           string `bson:"language"`
	Campaign           string `bson:"campaign"`
	GpsAdid            string `bson:"gps_adid"`
	ConversionDuration string `bson:"conversion_duration"`
	InstallFinishTime  string `bson:"install_finish_time"`
	ClickTime          string `bson:"click_time"`
	Creative           string `bson:"creative"`
	SdkVersion         string `bson:"sdk_version"`
	Country            string `bson:"country"`
	Platform           string `bson:"platform"`
	Ip                 string `bson:"ip"`
	CostType           string `bson:"cost_type"`
	Adid               string `bson:"adid"`
	Os                 string `bson:"os"`
	CreatedAt          string `bson:"created_at"`
	TrackerName        string `bson:"tracker_name"`
	AppVersion         string `bson:"app_version"`
	CostCurrency       string `bson:"cost_currency"`
	AppId              string `bson:"app_id"`
	MatchType          string `bson:"match_type"`
	Device             string `bson:"device"`
	UserAgent          string `bson:"user_agent"`
	Brand              string `bson:"brand"`
	InstallTime        string `bson:"install_time"`
	AdNetwork          string `bson:"ad_network"`
	CostAmount         string `bson:"cost_amount"`
	Adgroup            string `bson:"adgroup"`
	TrackerToken       string `bson:"tracker_token"`
	ActivityKind       string `bson:"activity_kind"`
	AppName            string `bson:"app_name"`
	InstalledAtHour    string `bson:"installed_at_hour"`
}

func Query(c *gin.Context) {
	query := c.Request.URL.Query()
	if query == nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "未接受参数",
		})
	}

	qMap := make(map[string]string)
	for q := range query {
		qMap[q] = c.Query(q)
	}
	qMap["insert_mongo_date"] = time.Now().Format("2006-01-02 15:04:05")
	//数据存入mongo
	// Set client options
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	//clientOptions := options.Client().ApplyURI("mongodb://47.90.66.58:27017")
	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	collection := client.Database("adjust").Collection("adjust_" + time.Now().Format("2006-01-02"))
	collection.InsertOne(context.TODO(), qMap)
	err = client.Disconnect(context.TODO())
	if err != nil {
		log.Fatal(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "adjust callback success",
	})

}

/**
生成csv文件
*/
func ExportCsv() {
	//clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	clientOptions := options.Client().ApplyURI("mongodb://47.90.66.58:27017")
	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	adjustTable := "adjust_" + time.Now().Format("2006-01-02")
	collection := client.Database("adjust").Collection(adjustTable)
	filter := bson.D{{}}
	cur, err := collection.Find(context.TODO(), filter)
	if err != nil {
		log.Fatal(err)
	}
	var results []*AdjustRes
	err = cur.All(context.TODO(), &results)
	fmt.Println(results)
	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}
	//遍历结束后关闭游标
	cur.Close(context.TODO())
	fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)
	err = client.Disconnect(context.TODO())

	// 创建一个 tutorials.csv 文件
	csvFile, err := os.Create(adjustTable + ".csv")
	// 初始化一个 csv writer，并通过这个 writer 写入数据到 csv 文件
	writer := csv.NewWriter(csvFile)
	for _, r := range results {
		// 将切片类型行数据写入 csv 文件
		line := []string{
			r.Language,
			r.Campaign,
			r.GpsAdid,
			r.ConversionDuration,
			r.InstallFinishTime,
			r.ClickTime,
			r.Creative,
			r.SdkVersion,
			r.Country,
			r.Platform,
			r.Ip,
			r.CostType,
			r.Adid,
			r.Os,
			r.CreatedAt,
			r.TrackerName,
			r.AppVersion,
			r.CostCurrency,
			r.AppId,
			r.MatchType,
			r.Device,
			r.UserAgent,
			r.Brand,
			r.InstallTime,
			r.AdNetwork,
			r.CostAmount,
			r.Adgroup,
			r.TrackerToken,
			r.ActivityKind,
			r.AppName,
			r.InstalledAtHour,
		}

		err := writer.Write(line)
		if err != nil {
			fmt.Println(err)
		}
	}
	// 将 writer 缓冲中的数据都推送到 csv 文件，至此就完成了数据写入到 csv 文件
	writer.Flush()
}
